package com.zdkj.subway.st.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.core.util.R;
import com.zdkj.common.data.mybatis.wrapper.CustomQueryWrapper;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.subway.st.entity.SwTkBlack;
import com.zdkj.subway.st.service.SwTkBlackService;
import com.zdkj.subway.st.util.DateUtilsSt;
import com.zdkj.subway.st.util.LocalDateConverter;
import com.zdkj.subway.st.util.LocalDateTimeConverter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;


/**
 * 黑名单管理
 *
 * @author chenbo
 * @date 2020-06-10 10:21:03
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swtkblack")
@Api(value = "swtkblack", tags = "黑名单管理管理")
public class SwTkBlackController {

    private static final String BLACK_STATUS_NOT = "0";
    private static final String BLACK_STATUS_YES = "1";
    private static final String APPLY_STATUS_NOSUBMIT = "0";
    private static final String APPLY_STATUS_SUBMIT = "1";
    private final SwTkBlackService swTkBlackService;

    /**
     * 分页查询
     *
     * @param page      分页对象
     * @param swTkBlack 黑名单管理
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwTkBlackPage(Page page, SwTkBlack swTkBlack) {
        List<String> dateCondition = swTkBlack.getDates1();
        LambdaQueryWrapper<SwTkBlack> queryWrapper = Wrappers.<SwTkBlack>query(swTkBlack).orderByDesc("submit_time").lambda()
                .eq(swTkBlack.getHandleStatus() != null, SwTkBlack::getHandleStatus, swTkBlack.getHandleStatus())
                .like(swTkBlack.getCardNum() != null, SwTkBlack::getCardNum, swTkBlack.getCardNum())
                .like(swTkBlack.getName() != null, SwTkBlack::getName, swTkBlack.getName());
        if (ObjectUtil.isNotEmpty(dateCondition)) {
            queryWrapper.between(SwTkBlack::getBlackTime, dateCondition.get(0), dateCondition.get(1));
        }
//        //有审批权限的人不能看未提交的
//        if (roleSP!=null){
//            return R.ok(swTkBlackService.page(page, Wrappers.query(init).lambda()
//                    .ne(roleSP==null?false:true,SwTkBlack::getHandleStatus,roleSP)
//                    .like(swTkBlack.getCardNum()==null?false:true,SwTkBlack::getCardNum,swTkBlack.getCardNum())
//                    .like(swTkBlack.getName()==null?false:true,SwTkBlack::getName,swTkBlack.getName())
//                    .between(dateFlag, SwTkBlack::getBlackTime, startDate, endDate)));
//        }
//        //有确认权限的人只能看审批通过的
//        if (roleQF!=null){
//            return R.ok(swTkBlackService.page(page, Wrappers.query(init).lambda()
//                    .eq(roleQF==null?false:true,SwTkBlack::getHandleStatus,roleQF)
//                    .eq(swTkBlack.getBlackStatus()==null?false:true,SwTkBlack::getBlackStatus,swTkBlack.getBlackStatus())
//                    .like(swTkBlack.getCardNum()==null?false:true,SwTkBlack::getCardNum,swTkBlack.getCardNum())
//                    .like(swTkBlack.getName()==null?false:true,SwTkBlack::getName,swTkBlack.getName())
//                    .between(dateFlag, SwTkBlack::getBlackTime, startDate, endDate)));
//        }
        return R.ok(swTkBlackService.page(page, queryWrapper));
    }


    /**
     * 通过id查询黑名单管理
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swTkBlackService.getById(id));
    }

    /**
     * 新增黑名单管理
     *
     * @param swTkBlack 黑名单管理
     * @return R
     */
    @ApiOperation(value = "新增黑名单管理", notes = "新增黑名单管理")
    @SysLog("新增黑名单管理")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('st_swtkblack_add')")
    public R save(@RequestBody SwTkBlack swTkBlack) {
        SwTkBlack defaultObj = ObjectUtils.getDefaultObj(SwTkBlack.class);
        BeanUtil.copyProperties(swTkBlack, defaultObj, ObjectUtils.getNullAndEmptyPropertyNames(swTkBlack));
        return R.ok(swTkBlackService.save(defaultObj));
    }

    /**
     * 提交黑名单管理
     *
     * @param list 黑名单管理
     * @return R
     */
    @ApiOperation(value = "提交黑名单管理", notes = "提交黑名单管理")
    @SysLog("提交黑名单管理")
    @PutMapping("submitBatch")
    @PreAuthorize("@pms.hasPermission('st_swtkblack_submitBatch')")
    public R submitBatch(@RequestBody List<SwTkBlack> list) {
        for (SwTkBlack swTkBlack : list) {
            if (swTkBlack.getHandleStatus().equals(APPLY_STATUS_NOSUBMIT)) {
                swTkBlack.setSubmitTime(LocalDateTime.now());
                swTkBlack.setHandleStatus(APPLY_STATUS_SUBMIT);
            } else {
                break;
            }
        }
        return R.ok(swTkBlackService.updateBatchById(list));
    }

    /**
     * 审批黑名单管理
     *
     * @param list 黑名单管理
     * @return R
     */
    @ApiOperation(value = "审批黑名单管理", notes = "审批黑名单管理")
    @SysLog("审批黑名单管理")
    @PutMapping("auditBatch")
    @PreAuthorize("@pms.hasPermission('st_swtkblack_auditBatch')")
    public R auditBatch(@RequestBody List<SwTkBlack> list) {
        for (SwTkBlack swTkBlack : list) {
            swTkBlack.setAuditTime(LocalDateTime.now());
        }
        return R.ok(swTkBlackService.updateBatchById(list));
    }

    /**
     * 确认黑名单管理
     *
     * @param list 确认黑名单管理
     * @return R
     */
    @ApiOperation(value = "确认黑名单管理", notes = "确认黑名单管理")
    @SysLog("确认黑名单管理")
    @PutMapping("confirmBatch")
    @PreAuthorize("@pms.hasPermission('st_swtkblack_confirmBatch')")
    public R confirmBatch(@RequestBody List<SwTkBlack> list) {
        for (SwTkBlack swTkBlack : list) {
            if (swTkBlack.getBlackStatus().equals(BLACK_STATUS_NOT)) {
                swTkBlack.setBlackTime(LocalDateTime.now());
                swTkBlack.setBlackStatus(BLACK_STATUS_YES);
            }
        }
        return R.ok(swTkBlackService.updateBatchById(list));
    }

    /**
     * 修改黑名单管理
     *
     * @param swTkBlack 黑名单管理
     * @return R
     */
    @ApiOperation(value = "修改黑名单管理", notes = "修改黑名单管理")
    @SysLog("修改黑名单管理")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('st_swtkblack_edit')")
    public R updateById(@RequestBody SwTkBlack swTkBlack) {
        return R.ok(swTkBlackService.updateById(swTkBlack));
    }

    /**
     * 通过ids删除黑名单管理
     *
     * @param ids ids
     * @return R
     */
    @ApiOperation(value = "通过ids删除黑名单管理", notes = "通过ids删除黑名单管理")
    @SysLog("通过ids删除黑名单管理")
    @DeleteMapping("/delBatch")
    @PreAuthorize("@pms.hasPermission('st_swtkblack_delBatch')")
    public R removeByIds(@RequestBody List<Integer> ids) {
        return R.ok(swTkBlackService.removeByIds(ids));
    }

    /**
     * 通过id删除黑名单管理
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除黑名单管理", notes = "通过id删除黑名单管理")
    @SysLog("通过id删除黑名单管理")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('st_swtkblack_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(swTkBlackService.removeById(id));
    }

    /**
     * 导出
     *
     * @param page      分页对象
     * @param swTkBlack 黑名单管理
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('st_swtkblack_export')")
    public void getSwStInvoiceBalanceExport(Page page, SwTkBlack swTkBlack, HttpServletResponse response) throws IOException {
        Page a = swTkBlackService.pageExport(page, new CustomQueryWrapper(SwTkBlack.class)
                .addDTO(swTkBlack)
                .addAlis("a")
                .addDelFlag(Boolean.TRUE)
                .init());
        // 写法1
        String fileName = URLEncoder.encode("黑名单管理", "UTF-8");
        //"C:\\Users\\Administrator\\Desktop\\" + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + DateUtilsSt.getDatetimeNowFormatter() + ".xlsx");
        EasyExcel.write(response.getOutputStream(), SwTkBlack.class).registerConverter(new LocalDateTimeConverter())
                .registerConverter(new LocalDateConverter()).sheet("黑名单管理").doWrite(a.getRecords());
    }

    @ApiOperation(value = "批量导入黑名单", notes = "批量导入黑名单")
    @SysLog("批量导入黑名单")
    @PostMapping("/saveBatch")
    @PreAuthorize("@pms.hasPermission('st_swtkblack_import')")
    public R saveBatch(@RequestParam("file") MultipartFile file) throws Exception {
        File excelFile = MultipartFileToFile.multipartFileToFile(file);
        return R.ok(swTkBlackService.saveBatchWithExcel(excelFile));
    }


}
